package utils;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtils {
    private static DataSource dataSource =null;

    static{
        try (
                InputStream is=JDBCUtils.class.getResourceAsStream("/jdbc.properties")
        ){
            Properties p = new Properties();
            p.load(is);
            dataSource = new DriverManagerDataSource(p.getProperty("url"), p.getProperty("username"), p.getProperty("password"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static JdbcTemplate getJDBCTemplate(){
        //创建JDBCTemplate对象并传入数据库连接池
        JdbcTemplate template = new JdbcTemplate(dataSource);
        return template;
    }

    /**
     * 获取数据库连接池
     * @return
     */
    public static DataSource getDataSource(){
        return dataSource;
    }

    /**
     * 开始线程绑定 +获取连接
     * @return
     */
    public static Connection startTransaction(){
        if (!TransactionSynchronizationManager.isSynchronizationActive()){
            TransactionSynchronizationManager.initSynchronization();
        }
        Connection connection =DataSourceUtils.getConnection(dataSource);
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    /**
     * 提交事务
     * @param conn
     */
    public static void commit(Connection conn){
        try {
            conn.commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            clear(conn);
        }
    }

    /**
     * 回滚事务
     * @param conn
     */
    public static void rollback(Connection conn){
        try {
            conn.rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            clear(conn);
        }
    }


    /**
     * 解除线程绑定+释放资源+归还连接到线程池
     * @param conn
     */
    public static void clear(Connection conn){
        //清除线程绑定的资源
        TransactionSynchronizationManager.clear();
        TransactionSynchronizationManager.unbindResourceIfPossible(dataSource);
        //归还数据库连接至连接池
        if (conn!=null){//非空判断，判断为空再归还
            DataSourceUtils.releaseConnection(conn,dataSource);
        }
    }

}
